import {NzMessageService, NzNotificationService} from 'ng-zorro-antd';
import {Component, Inject, OnInit} from '@angular/core';
import {_HttpClient} from '@delon/theme';
import {UtilityService} from '../../../service/utils.service';
import {View} from '@antv/data-set';
import {appConfig} from '../../../service/common';
import {DA_SERVICE_TOKEN, ITokenService} from '@delon/auth';
import * as moment from 'moment';

@Component({
    selector: 'app-dashboard-v1',
    templateUrl: './v1.component.html',
     styleUrls: ['./v1.component.less'],
})
export class DashboardV1Component implements OnInit {

    constructor(
      private http: _HttpClient,
      public msg: NzMessageService,
      private utilityService: UtilityService,
      private nznot: NzNotificationService,
        @Inject(DA_SERVICE_TOKEN) private tokenService: ITokenService,
         ) { }

    todoData: any[] = [
        { completed: true, avatar: '1', name: '苏先生', content: `请告诉我，我应该说点什么好？` },
        { completed: false, avatar: '2', name: 'はなさき', content: `ハルカソラトキヘダツヒカリ` },
        { completed: false, avatar: '3', name: 'cipchk', content: `this world was never meant for one as beautiful as you.` },
        { completed: false, avatar: '4', name: 'Kent', content: `my heart is beating with hers` },
        { completed: false, avatar: '5', name: 'Are you', content: `They always said that I love beautiful girl than my friends` },
        { completed: false, avatar: '6', name: 'Forever', content: `Walking through green fields ，sunshine in my eyes.` }
    ];

    quickMenu = false;

    webSite: any[] = [ ];
    salesData: any[] =  [ ];
    offlineChartData: any[] = [];
    tabs = [
    {
      index: 1,
      title:'月度重点追踪'
    },
    {
      index: 2,
        title:'个人重点追踪'
    }
  ];


 scale = [{
  dataKey: 'sales',
  tickInterval: 20,
}];
 scaleProfiles =[{
  dataKey: 'count',
  tickInterval: 20,
}];
 forceFit: boolean = true;
 toufangforceFit: boolean = true;
    height: number = 250;
    toufangheight: number = 250;
    toufangdata= []
    toufangsourceData = [];
    dataProfiles = []
 toufangscale = [{
  dataKey: 'percent',
  // title: null,
  // position:'left',
  min: 0,
  formatter: '.0%',
}];

  adjust = [{
    type: 'dodge',
    marginRatio: 1 / 32,
  }];

   pieStyle = {
    stroke: "#fff",
    lineWidth: 1
  };
  labelConfig = ['percent', {
    offset: -40,
    textStyle: {
      rotate: 0,
      textAlign: 'center',
      shadowBlur: 2,
      shadowColor: 'rgba(0, 0, 0, .45)'
    }
  }];

itemTpl = '<li><span style="background-color:{color};text-align:right" class="g2-tooltip-marker"></span>{percent}<p>{name}: {value}</p></li>';
tooltip = [
  'item*count*percent', (item, count,percent) => {
    percent = (percent * 100).toFixed(2) + '%';
    return {
      name: item,
      value: count,
      percent:percent
    };
  },
];
sourceData = [];
 workTypeWord =[

          {label: '需求', value: 'D', selector:false,if:false},
          {label: '项目', value: 'P', selector:false,if:false},
          {label: '生产事件', value: 'E', selector:false,if:true}

    ]
    itemStatus = [
          {label: '开发中', value: 0, selector:false},
          {label: '已投产', value: 1, selector:false},
         {label: '已取消', value: 2, selector:false}
    ]
    usertags=[
      "有想法",
      "有责任",
      "有心",
      "有动力",
    ]
  data:any;
  token:any;
  padding= [ 20, 20, 60, 30]
  isSHow = false;
  dateRange = []

  user={
    name:'',
    role:''
  };
  greetings:string;
    ngOnInit() {
      this.token  = this.tokenService.get().seniortoken;
      this.user = JSON.parse(localStorage.getItem('_token'))
      this.getData()
      this.getList()
     let now = new Date()
     let hour = now.getHours()
if(hour < 6){ this.greetings="凌晨好！"}
else if (hour < 9){ this.greetings="早上好！"}
else if (hour < 12){this.greetings="上午好！"}
else if (hour < 14){this.greetings="中午好！"}
else if (hour < 17){this.greetings="下午好！"}
else if (hour < 19){this.greetings="傍晚好！"}
else if (hour < 22){this.greetings="晚上好！"}
else {this.greetings="这么晚了，该休息了~"}
    }
    isCaocuo = false;
    headerDate= [  // 配置表头内容
        { value: '工作项名称', key: 'itemName', isclick: false },
        { value: '负责人', key: 'owner', isclick: false },
        { value: '投产时间', key: 'deliveryTime', isclick: false },
        { value: '标签', key: 'itemLablesWork', isclick: false },
        { value: '测试情况', key: 'profilseNames', isclick: false },
    ];

    isdata=[]
    isButton = true;
    SelectChange(even){
   
      if(even.index === 0){
        this.isButton = true
      }else{
              this.isButton = false;
      }
    }
      getNowFormatDate(date) {
        // let date = new Date();
        let seperator1 = "-";
        let year = date.getFullYear();
        let month = date.getMonth() + 1;
        let strDate = date.getDate();
        if (month >= 1 && month <= 9) {
            month = "0" + month;
        }
        if (strDate >= 0 && strDate <= 9) {
            strDate = "0" + strDate;
        }
        var currentdate = year + seperator1 + month + seperator1 + strDate;
        return currentdate;
    }
    total = 0
    profilesCount:number;
    workitemCount:number;
    deliveryCount:number;
     deliveryResults = appConfig.Enumeration.deliveryResults
     listloading = false;
     ismodaloading = false;
     beginTime = null
     endTime = null
     reset(){
       this.dateRange = []
       this.isSHow = false;
         this.workTypeWord.forEach(i=>{
           i.selector = false
         })
             this.tags.forEach(i=>{
               i.istrue = false;
             })
             this.getList()
     }
     additemLable(event){
      
        this.itemLable.forEach(i=>{
            this.tags.forEach(j=>{
              if(i===j.name){
                j.istrue = true;
              }
            })
        })
     }
     getList(it?){

      this.beginTime = null;
       this.endTime = null
       let obj = []
       if(this.dateRange[0]){
               this.beginTime = this.getNowFormatDate(this.dateRange[0])
       }
       if(this.dateRange[1]){
               this.endTime = this.getNowFormatDate(this.dateRange[1])
       }


       let objs = {
         itemLables:[],
         workType:'',
         beginTime:this.beginTime,
         endTime:this.endTime
       }
         if(this.tags.length !== 0){
         this.tags.forEach(i=>{
           if(i.istrue){
             objs.itemLables.push(i.name)
           }
         })
       }

           let stc = [];
           this.workTypeWord.forEach(i=>{
             if(it){
                if(i.label === it.label){
              i.selector = !i.selector
            }else{
              i.selector = false
            }

             }

             if(i.selector){
               this.isSHow = true;
                objs.workType = i.value
                stc.push(stc)
              }


        })
        if(stc.length===0){
            this.isSHow = false;
        }

        this.listloading = true;
        this.ismodaloading = true;
        this.utilityService.postData(appConfig.testUrl  + '/sWorkitem/workProfiseDetail',objs)
               .subscribe(
                (res) => {
               this.total =  res.result.length
             this.ismodaloading = false;
             this.searchVisible = false;
           this.listloading = false;
            res.result.forEach(it => {
              if(it.itemLable!=''){
                  it.itemLablesWork = it.itemLable.split(',')
              }else{
                  it.itemLablesWork = []
              }

              it.deliveryTime = moment(it.deliveryTime).format('YYYY-MM-DD');
            });
            this.isdata = res.result;
                }, (error) => {
                       this.ismodaloading = false
                     this.searchVisible = false;
                    this.nznot.create('error', error.code,  error.msg);
                })

     }
    getData(){
        this.isShow = 1;
         this.utilityService.getData(appConfig.testUrl  + '/sWorkitem/homepageShow')
            .subscribe(
                (val) => {
                  let obj = []
                 val.result.workTypeStatusGroupCount.forEach(it => {
                   it['开发中'] = it['0']
                   it['已投产'] = it['1']
                   it['已取消'] = it['2']

                 this.workTypeWord.forEach(i=>{
                   if(i.value === it.workType){
                     it.workType = i.label

                   }
                 })
                  obj.push({workType: it.workType,'开发中':parseInt(it['0']),'已投产':parseInt(it['1']),'已取消':parseInt(it['2'])})
                });
                this.sourceData = obj
              const dv = new View().source(this.sourceData);
              dv.transform({
                type: 'fold',
                fields: ['开发中', '已取消', '已投产'],
                key: '开发状态',
                value: '工作项数量',
              });
              this.data = dv.rows;
              this.profilesCount = val.result.profilesCount
                this.workitemCount = val.result.workitemCount
                  this.deliveryCount = val.result.deliveryCount
              val.result.deliveryResultGroupCount.forEach(el=>{
                 this.deliveryResults.forEach(i=>{
                      if(el.deliveryResult === i.key){
                        el['item'] = i.value;
                      }
                 })
              })
              this.toufangsourceData =  val.result.deliveryResultGroupCount
              const dvv = new View().source(this.toufangsourceData);
            dvv.transform({
              type: 'percent',
              field: 'count',
              dimension: 'item',
              as: 'percent'
            });
        this.toufangdata = dvv.rows;
        this.dataProfiles = val.result.deliveryProfilesDetails
                  console.log(val.result.deliveryResultGroupCount)
                     console.log( this.toufangdata)
                }, (error) => {

                    this.nznot.create('error', error.code,  error.msg);
                }
            );
    }
    isShow = 1;
    isShowClick(it){
     this.isShow = it;

    }
      selecttags = [];
      itemLable = []
    checkTabs(event){
     console.log(event)
     setTimeout(()=>{

        this.utilityService.postData(appConfig.testUrl  +'/sWorkitem/lable' , {lableName:event})
            .subscribe(
                (val) => {
                    this.selecttags = val.result

               },(error)=>{
            this.nznot.create('error', error.code , error.msg);
            });


    },300);
}
    monitorHandler(it){

    }
    searchVisible = false;
    tags = []
    getModal(){
        //  this.searchVisible = true;
          this.tags = []
           this.utilityService.getData(appConfig.testUrl  + '/sWorkitem/lableAll')
            .subscribe(
                (val) => {
                  console.log(val)
                    this.searchVisible = true;

                    val.result.forEach(i=>{
                       this.tags.push({name:i,istrue:false})
                    })

                },(error)=>{
                     this.nznot.create('error',error.code,  error.msg);
                })
    }

    tagClick(it){
      //  let obj= []
      this.tags.forEach(i=>{
        if(it.name === i.name){
          i.istrue = !i.istrue

        }
        //  if(i.istrue){
        //     obj.push(i.name)
        //   }
      })
      // this.itemLable = obj;

    }

}
